import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import ErrorRouters from './errorPages' // 出错页
import wrap from '@/components/layout/wrap.vue'

Vue.use(VueRouter)

let menu = store.getters.GET_MENU

// 菜单路由
const menuRouters = [
  {
    path: '/',
    component: wrap,
    children: []
  },
  {
    path: '*',
    redirect: '/errorPage/404'
  }
]
// 生成菜单路由
const setMenuRouters = (item) => {
  menuRouters[0].children.push({
    path: item.path ? item.path : '/',
    component: (resolve) => require([`@/views${item.src}`], resolve),
    meta: {
      keepAlive: item.keepAlive, // 是否缓存
      hideTag: item.hideTag, // 标签是否隐藏（优先级高于父级标签高亮显示）
      parent: item.parent // 父级path（子页面打开时所关联的父级tag）
    }
  })
}
// 循环菜单生成路由
const getRouters = (menuList) => {
  for (const item of menuList) {
    if (item.subMenu.length > 0) {
      getRouters(item.subMenu)
    } else {
      setMenuRouters(item)
    }
  }
}

getRouters(menu)

// 创建路由
const createRouter = () => new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      component: (resolve) => require(['@/views/login.vue'], resolve)
    },
    ErrorRouters,
    ...menuRouters
  ]
})

const router = createRouter()

// 路由权限
router.beforeEach((to, from, next) => {
  NProgress.start() // 进度条-开启
  if (to.path === '/login' || store.getters.GET_TOKEN) {
    next()
  } else {
    next({ path: '/login' })
  }
})
router.afterEach((to, from) => {
  window.scrollTo(0, 0) // 每次路由改变滚动条都回到顶部
  NProgress.done() // 进度条-关闭
})

export default router

// 生成菜单路由-获取菜单后调用
export const initMenuRouter = () => {
  if (menu.length === 0) {
    menu = store.getters.GET_MENU
    getRouters(menu)
    router.addRoutes(menuRouters)
  }
}
